<template>
  <div class="iframe_box">
    <div
      class="load"
      element-loading-text="拼命加载中"
    ></div>
    <div class="iframe_wrapper">
    <iframe
      :src="`../../../../static/font.html`"
      width="100%"
      height="100%"
      ref="iframeDom"
    ></iframe>
    </div>
  </div>
</template>
<script>
import * as echarts from 'echarts'

export default {
  data () {
    return {
      dataForm: {
        key: '',
        areaAlarmNo: '',
        areaId: '',
        lableId: '',
        lableEmployid: '',
        alarmTime: ''
      },
      code: null,
      apiUrl: null,
      iframeWin: {},
      firstData: [{
        id: "2023",
        name: "wpc"
      }],
      dataList: [],
      dataList1: [{}],
      dataJson: {
        areaAlarmNo: '',
        areaId: '',
        lableId: '',
        lableEmployid: '',
        alarmTime: '',
        chartLine: null,
        chartBar: null,
        chartPie: null,
        chartScatter: null
      },
      dataJson1: [],
      alarmNum: 0,
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      dataListSelections: [],
      addOrUpdateVisible: false,
      showSessionId: '',
      total: [],
      total1: [],
      total2: []
    }
  },
  created () {
    this.code = this.$route.params.code;
    this.apiUrl = process.env.VUE_APP_URL;
  },
  mounted () {
    //测试设备ws接口token
    this.devicesData();
    // this.initWebSocket()
    // this.getuser()
    // this.test1()
    // this.test2()
    let iframeWin = this.$refs.iframeDom.contentWindow;
    const p1 = new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve(this.total1)
      }, 2000)
    })
    const p2 = new Promise((resolve, reject) => {
      setTimeout(() => {
       resolve(this.total2)
      }, 2000)
    })
    Promise.all([
      p1,
      p2
    ]).then((data) => {
      console.log("Begin")
      console.log(data)
      iframeWin.postMessage({
        total: data
      },"*")
    })
  },
  activated () {


  },
  methods: {
    //devices ws
    devicesData(){
      this.$http({
        url: this.$http.adornUrl('/api/token'),
        method: 'get'
      }).then(({data}) => {
        if (data) {
          // this.token = data;
          let URL = "wss://thingsboard.cmhijs.cn:8443/api/ws/plugins/telemetry?" + "token=" + data;
          let ws = new WebSocket(URL);
          ws.onopen = () => {
            console.log("连接成功！")
            // Web Socket 已连接上，使用 send() 方法发送数据
            console.log('发送数据中。。。')
            // ws.send('{"attrSubCmds":[],"historyCmds":[],"tsSubCmds":[{"cmdId":111,"entityId":"922ffb40-da6a-11ed-bbb0-dde55e1f139a","entityType":"DEVICE","keys":"DDE5.Gruppe_3.ProcessTime32","scope":"LATEST_TELEMETRY"}]}')
            console.log('数据发送完成。')
          }
          ws.onmessage = evt => {    //后端发来的消息接收（注意数据放在evt的data中并且是个JSON字符串，需要parse成JSON对象去使用）
            //let hhlist = JSON.parse(evt);

            console.log("接收中。。。")
            console.log(evt.data)
            console.log('接收完成')
            //具体业务逻辑

          }
          ws.onclose = function () {
            // 关闭 websocket
            console.log('连接已关闭...')
          }
          // 路由跳转时结束websocket链接
          this.$router.afterEach(function () {
            ws.close()
          })
        }
      }).catch(error => {
        console.error('token错误',error);
      })
    },
    //测试vue websocket
    initWebSocket(){ //初始化weosocket
      const $vm = this
      let ws = new WebSocket('ws://localhost:8089/renren-fast/websocket/pos');  //这里new 一个WebSocket对象将连接地址传入（这个连接地址很重要，很多情况连接不上就是连接地址没用写对）
      ws.onopen = () => {
        // Web Socket 已连接上，使用 send() 方法发送数据
        // console.log('发送数据中。。。')
        // ws.send('你好')
        // console.log('数据发送完成。')
      }
      ws.onmessage = evt => {    //后端发来的消息接收（注意数据放在evt的data中并且是个JSON字符串，需要parse成JSON对象去使用）
        //let hhlist = JSON.parse(evt);

        console.log("接收中。。。")
        console.log(evt.data)
        console.log('接收完成')
        //具体业务逻辑
        this.total1 = evt.data

        // $vm.$set($vm.panelData,"rsumhh",psu) //这里是 vue给一些已经改变了的图表数据后，显示内容没用变化时用的。（直接用=去赋值界面的显示是不会变的 Echarts 图表就是需要用 set去改变值的变化）
        // console.log('数据已接收...')

      }
      ws.onclose = function () {
        // 关闭 websocket
        console.log('连接已关闭...')
      }
      // 路由跳转时结束websocket链接
      this.$router.afterEach(function () {
        ws.close()
      })
    },
    posChart8(){
      this.$http({
        url: this.$http.adornUrl('/tbposition/tbposition/list'),
        method: 'get'
      }).then(({data}) => {
       this.total = data.page.list;
        //console.log(total)
        this.$http({
          url: this.$http.adornUrl('/equipinfo/equipinfotable/num'),
          method: 'get'
        }).then(({data}) => {
          this.total1 = data
          // console.log("---------")
          this.iframeWin = this.$refs.iframeDom.contentWindow
          setTimeout(
            () => {
              this.iframeWin.postMessage({
                params: this.total,
                params1: this.total1
              }, '*')
            }, 200);
        })
      })
    },
  }
}
</script>
<style lang="scss" scoped>
.iframe_box {
  width: 100%;
  height: 100%;
  position: relative;
}

.iframe_wrapper {
  width: 100%;
  padding-top: 56.25%; /* 16:9 ratio, for an aspect ratio of 4:3 use 75% */
  position: relative;
}

iframe {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
</style>


